/**
 * @author yinyuejia
 * @file 路由处理
 */

import { createRouter, createWebHashHistory } from 'vue-router';
import NProgress from 'nprogress';
import store from '@/store';
import 'nprogress/nprogress.css';
import constantRoutes, { businessRoute } from './constantRoute';
import config from '@/config';
import i18n from '@/locale';
import application from '@/utils/app';

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes: constantRoutes.concat(businessRoute),
});

/* eslint-disable */
// 劫持路由搞重定向相关
router.beforeEach((to: any, from: any, next: any) => {
  // 进度条
  NProgress.start();
  if (!to.path.includes('login')) {
    store.commit('reloadUser');
    store.commit('reloadMenu');
  }
  if (!store.getters.isLogin) {
    store.commit('reloadUser');
    if (to.path === '/login') {
      next();
    } else {
      next({
        name: 'Login',
      });
    }
  } else if (to.path === '/login' && store.getters.isLogin) {
    if (router.hasRoute('Home')) {
      store.commit('reload');
      next({
        name: 'Home',
      });
    } else {
      // @ts-ignore
      store.commit('setRoute');
      next('/home');
    }
  } else if (to.path === '/home' && store.getters.isLogin) {
    if (router.hasRoute('Home')) {
      store.commit('reload');
      next();
    } else {
      store.commit('setRoute');
      next('/home');
    }
  }
  // @ts-ignore
  else if (!store.state.menu.routeLoaded) {
    store.commit('setRoute');
    next(to.fullPath);
  } else {
    store.commit('reload');
    next();
  }
  // const ignoreAuth = to.meta.auth === false;
});
/* eslint-enable */

router.afterEach((to: any) => {
  application.routerFinished(to);
  document.title = to.meta.title
    ? // @ts-ignore
      `${i18n.global.t(to.meta.title)} - ${config.system.APP_NAME}`
    : `${config.system.APP_NAME}`;
  NProgress.done();
});

router.onError(() => {
  NProgress.done();
});

export default router;
